package com.myorigin.weblog.jwt.handle;

import com.myorigin.weblog.common.utils.Response;
import com.myorigin.weblog.jwt.model.LoginRspVO;
import com.myorigin.weblog.jwt.utils.JwtTokenHelper;
import com.myorigin.weblog.jwt.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义认证成功处理器 RestAuthenticationSuccessHandler
 * 用户登录后，我们还需要处理其对应的结果，如登录成功，则返回 Token 令牌，登录失败，则返回对应的提示信息。
 * 在 Spring Security 中，AuthenticationFailureHandler 和 AuthenticationSuccessHandler 是用于处理身份验证失败和成功的接口。
 * 它们允许您在用户身份验证过程中自定义响应，以便更好地控制和定制用户体验。
 */
@Component
@Slf4j
public class RestAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTokenHelper jwtTokenHelper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从 authentication 对象中获取用户的 UserDetails 实例，这里是获取用户的用户名
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        // 通过用户名生成token
        String username = userDetails.getUsername();
        String token = jwtTokenHelper.generateToken(username);

        //返回token
        LoginRspVO loginRspVO = new LoginRspVO().builder().token(token).build();

        ResultUtil.ok(response, Response.success(loginRspVO));
    }

}
